package com.netty.chatRoom.server.Handler;

import com.netty.chatRoom.message.GroupJoinRequestMessage;
import com.netty.chatRoom.message.GroupJoinResponseMessage;
import com.netty.chatRoom.message.GroupQuitResponseMessage;
import com.netty.chatRoom.server.session.GroupSessionFactory;
import com.netty.chatRoom.server.session.SessionFactory;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.Set;

@ChannelHandler.Sharable
public class GroupJoinRequestMessageHandler extends SimpleChannelInboundHandler<GroupJoinRequestMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, GroupJoinRequestMessage groupJoinRequestMessage) throws Exception {
        // 加入群聊
        String groupName = groupJoinRequestMessage.getGroupName();
        String username = groupJoinRequestMessage.getUsername();
        Set<String> members = GroupSessionFactory.getGroupSession().getMembers(groupName);
        if (members.size()<=0){
            channelHandlerContext.writeAndFlush(new GroupJoinResponseMessage(false,"群聊【"+groupName+"】不存在"));
        }else {
            GroupSessionFactory.getGroupSession().joinMember(groupName,username);
            channelHandlerContext.writeAndFlush(new GroupJoinResponseMessage(true,"加入群聊【"+groupName+"】成功"));
            for (String member : members) {
                if(!member.equals(username)){
                    Channel channel = SessionFactory.getSession().getChannel(member);
                    if (channel!=null){
                        channel.writeAndFlush(new GroupQuitResponseMessage(true,String.format("用户【%s】已加入群聊【%s】，打个招呼吧~~",username,groupName)));
                    }
                }
            }
        }
    }
}
